package com.rover.system.service;


import com.common.UploadFile;

import com.common.swftools.SwfToolsUtil;
import com.grid.DataGrid;
import com.grid.Page;
import com.rover.system.dao.BaseDao;
import com.rover.system.entity.User;
import com.utils.*;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: rover
 * Date: 13-8-31
 * Time: 上午9:15
 * 通用service    (如果要使用接口，则所有继承BaseService的类都要使用接口开发)
 */
@Service("baseService")
@Transactional
public class BaseService {
    @Autowired
    protected BaseDao dao;

    /*
     * @return 当前登录用户
     * */
    public User getActiveUser(){
    	Subject subject = SecurityUtils.getSubject();
		String loginName = (String) subject.getPrincipal();
		if (StringUtils.isNotBlank(loginName)) {
			List<User> users = dao.findHql("from User u where u.loginName='"
					+ loginName + "'", null);
			if (null != users && users.size() != 0) {
				return users.get(0);
			}
		}
		return null;
    }
    

    public <T> DataGrid query(Page page) throws Exception {
        DataGrid dataGrid = new DataGrid();
        List<T> li = dao.<T>findPageHql(page.getHQL(), page.getWhereParams(), page.getPageNo(),
                page.getPageSize());
        dataGrid.setResult(li);
        dataGrid.setTotalCount(dao.countHql(page.getHQLTotalCount(), page.getWhereParams()));
        return dataGrid;

    }


    public <T> void save(T entity) {
        dao.save(entity);
    }


    public <T> void saveOrUpdate(T entity) {
        dao.saveOrUpdate(entity);
    }


    public <T> void delete(T entity) {
        dao.delete(entity);
    }


    public <T> void delete(Class c, Serializable id) {
        dao.delete(c, id);
    }
     /*
     *     根据批量主键删除数据
     * @param   c        要删除的对象
     * @param   list    要删除的列表
     *
     */
    public  void delete(Class c, List<Integer> list){
        dao.delete(c,list);
    }

    public <T> void batchSave(List<T> entitys) {
        dao.batchSave(entitys);
    }


    public <T> T getEntity(Class entityName, Serializable id) {
        return dao.get(entityName, id);  //To change body of implemented methods use File | Settings | File Templates.
    }


    public <T> List<T> getList(Class entityClass) {
        return dao.findHql("from " + entityClass.getSimpleName(),null);  //To change body of implemented methods use File | Settings | File Templates.
    }


    public <T> T findUniqueByProperty(Class<T> entityClass, String propertyName, Object value) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(propertyName, value);
        List list = dao.findHql("from " + entityClass.getSimpleName() + " where " + propertyName + ":" + propertyName, params);
        if (list.size() > 0)
            return (T) list.get(0);
        else
            return null;
    }

    /**
     * 按属性查找对象列表.
     *
     * @param entityClass  实体类
     * @param propertyName 属性
     * @param value        值
     * @return
     */

    public <T> List<T> findByProperty(Class<T> entityClass, String propertyName, Object value) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(propertyName, value);
        return dao.findHql("from " + entityClass.getSimpleName() + " where " + propertyName + ":" + propertyName, params);  //To change body of implemented methods use File | Settings | File Templates.
    }


    /**
     * 文件上传
     *
     * @param uploadFile
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public Object uploadFile(UploadFile uploadFile) {
        Object object = uploadFile.getObject();
        if(uploadFile.getFileKey()!=null)
        {
            dao.update(object);
        }
        else {
            try {
                uploadFile.getMultipartRequest().setCharacterEncoding("UTF-8");
                MultipartHttpServletRequest multipartRequest = uploadFile.getMultipartRequest();
                ReflectHelper reflectHelper = new ReflectHelper(uploadFile.getObject());
                String uploadbasepath = uploadFile.getBasePath();// 文件上传根目录
                if (uploadbasepath == null) {
                    uploadbasepath = ResourceUtil.getConfigByName("uploadpath");
                }
                Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
                // 文件数据库保存路径
                String path = "\\"+uploadbasepath + "\\";// 文件保存在硬盘的相对路径
                String realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/") + path;// 文件的硬盘真实路径
                File file = new File(realPath);
                if (!file.exists()) {
                    file.mkdir();// 创建根目录
                }
                if (uploadFile.getCusPath() != null) {
                    realPath += uploadFile.getCusPath() + "\\";
                    path += uploadFile.getCusPath() + "\\";
                    file = new File(realPath);
                    if (!file.exists()) {
                        file.mkdir();// 创建文件自定义子目录
                    }
                }
                else {
                    realPath += DateUtil.getDataString(DateUtil.yyyyMMdd) + "\\";
                    path += DateUtil.getDataString(DateUtil.yyyyMMdd) + "\\";
                    file = new File(realPath);
                    if (!file.exists()) {
                        file.mkdir();// 创建文件时间子目录
                    }
                }
                String entityName = uploadFile.getObject().getClass().getSimpleName();
                // 设置文件上传路径
//                if (entityName.equals("TSTemplate")) {
//                    realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/") + ResourceUtil.getConfigByName("templatepath") + "/";
//                    path = ResourceUtil.getConfigByName("templatepath") + "/";
//                } else if (entityName.equals("TSIcon")) {
//                    realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/") + uploadFile.getCusPath() + "/";
//                    path = uploadFile.getCusPath() + "/";
//                }
                String fileName = "";
                String swfName = "";
                for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                    MultipartFile mf = entity.getValue();// 获取上传文件对象
                    fileName = mf.getOriginalFilename();// 获取文件名
                    swfName = PinyinUtil.getPinYinHeadChar(FileUtil.getFilePrefix(fileName));// 取文件名首字母作为SWF文件名
                    String extend = FileUtil.getExtend(fileName);// 获取文件扩展名
                    String myfilename="";
                    String noextfilename="";//不带扩展名
                    if(uploadFile.isRename())
                    {

                        noextfilename=DateUtil.getDataString(DateUtil.yyyymmddhhmmss);//自定义文件名称
                        myfilename=noextfilename+"."+extend;//自定义文件名称
                    }
                    else {
                        myfilename=fileName;
                    }

                    String savePath = realPath + myfilename;// 文件保存全路径
                    String fileprefixName = FileUtil.getFilePrefix(fileName);
                    if (uploadFile.getTitleField() != null) {
                        reflectHelper.setMethodValue(uploadFile.getTitleField(), fileprefixName);// 动态调用set方法给文件对象标题赋值
                    }
                    if (uploadFile.getExtend() != null) {
                        // 动态调用 set方法给文件对象内容赋值
                        reflectHelper.setMethodValue(uploadFile.getExtend(), extend);
                    }
                    if (uploadFile.getByteField() != null) {
                        // 二进制文件保存在数据库中
                        reflectHelper.setMethodValue(uploadFile.getByteField(), StreamUtil.InputStreamTOByte(mf.getInputStream()));
                    }
                    if (uploadFile.getSize() != null) {
                        //    文件大小
                        reflectHelper.setMethodValue(uploadFile.getSize(),mf.getSize());
                    }
                    File savefile = new File(savePath);
                    if (uploadFile.getRealPath() != null) {
                        // 设置文件数据库的物理路径
                        reflectHelper.setMethodValue(uploadFile.getRealPath(), path + myfilename);
                    }

                    saveOrUpdate(object);
                    // 文件拷贝到指定硬盘目录
                    FileCopyUtils.copy(mf.getBytes(), savefile);
//				if (uploadFile.getSwfpath() != null) {
//					// 转SWF
//					reflectHelper.setMethodValue(uploadFile.getSwfpath(), path + swfName + ".swf");
//					SwfToolsUtil.convert2SWF(savePath);
//				}
//				FileCopyUtils.copy(mf.getBytes(), savefile);
                    if (uploadFile.getSwfpath() != null) {
                        // 转SWF
                        reflectHelper.setMethodValue(uploadFile.getSwfpath(), path + FileUtil.getFilePrefix(myfilename) + ".swf");
                       SwfToolsUtil.convert2SWF(savePath);
                    }

                }
            } catch (Exception e1) {
            }
        }
        return object;
    }

    /**
     * 文件下载或预览
     *
     * @param uploadFile
     * @throws Exception
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public HttpServletResponse viewOrDownloadFile(UploadFile uploadFile) {
        uploadFile.getResponse().setContentType("UTF-8");
        uploadFile.getResponse().setCharacterEncoding("UTF-8");
        InputStream bis = null;
        BufferedOutputStream bos = null;
        HttpServletResponse response = uploadFile.getResponse();
        HttpServletRequest request = uploadFile.getRequest();
        String ctxPath = request.getSession().getServletContext().getRealPath("/");
        String downLoadPath = "";
        long fileLength = 0;
        if (uploadFile.getRealPath() != null&&uploadFile.getContent() == null) {
            downLoadPath = ctxPath + uploadFile.getRealPath();
            fileLength = new File(downLoadPath).length();
            try {
                bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            if (uploadFile.getContent() != null)
                bis = new ByteArrayInputStream(uploadFile.getContent());
            fileLength = uploadFile.getContent().length;
        }
        try {
            if (!uploadFile.isView() && uploadFile.getExtend() != null) {
                if (uploadFile.getExtend().equals("text")) {
                    response.setContentType("text/plain;");
                } else if (uploadFile.getExtend().equals("doc")) {
                    response.setContentType("application/msword;");
                } else if (uploadFile.getExtend().equals("xls")) {
                    response.setContentType("application/ms-excel;");
                } else if (uploadFile.getExtend().equals("pdf")) {
                    response.setContentType("application/pdf;");
                } else if (uploadFile.getExtend().equals("jpg") || uploadFile.getExtend().equals("jpeg")) {
                    response.setContentType("image/jpeg;");
                } else {
                    response.setContentType("application/x-msdownload;");
                }
                response.setHeader("Content-disposition", "attachment; filename=" + new String((uploadFile.getTitleField() + "." + uploadFile.getExtend()).getBytes("GBK"), "ISO8859-1"));
                response.setHeader("Content-Length", String.valueOf(fileLength));
            }
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
